package com.java.control.impl;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.java.common.CommonUtil;
import com.java.common.ImageCaptchaService;
import com.java.control.AuthorizationCredit;
import com.java.mis.AdminLoginInfo;
import com.java.mis.LoginMessage;

/**
 * 用户登录
 * @author wqf
 * @version  Nov 25, 2011 9:26:07 AM
 */
public class LoginController extends SimpleFormController {
	
	public LoginController(){
		this.setCommandClass(AdminLoginInfo.class);
	}
	
	protected ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse response,Object command,BindException errors)
    throws Exception{
		AdminLoginInfo user = (AdminLoginInfo)command;
		if(StringUtils.isBlank(user.getAccount())||StringUtils.isBlank(user.getPassword())){
			request.setAttribute("message", "用户名或密码不能为空！");
			return this.showForm(request, errors, this.getFormView());
		}
		if(StringUtils.isBlank(user.getValidateCode())){
			request.setAttribute("message", "验证码不能为空！");
			return this.showForm(request, errors, this.getFormView());
		}else{
			if(ImageCaptchaService.validate(request, user.getValidateCode())==false){
				request.setAttribute("message", "验证码不正确！");
				return this.showForm(request, errors, this.getFormView());
			}
		}
		LoginMessage loginMessage = this.authorizationCredit.login(request, user.getAccount(), user.getPassword());
		if(loginMessage==LoginMessage.NOFOUND){
			request.setAttribute("message", "系统找不到此用户，请确认输入用户名是否正确！");
			return this.showForm(request, errors, this.getFormView());
		}
		
		if(loginMessage==LoginMessage.ERROR){
			request.setAttribute("message", "对不起，用户名或密码输入错误，请重新输入！");
			return this.showForm(request, errors, this.getFormView());
		}
		
		if(loginMessage==LoginMessage.LIMIT){
			request.setAttribute("message", "对不起，此账号被限制登录！");
			return this.showForm(request, errors, this.getFormView());
		}
	
		CommonUtil.redirectURL(request, response, this.getSuccessView());
		return null;
		
	}
	
	private AuthorizationCredit authorizationCredit;

	public void setAuthorizationCredit(AuthorizationCredit authorizationCredit) {
		this.authorizationCredit = authorizationCredit;
	}

}
